﻿using System.Data;
using System.Linq;
using System.Web.Mvc;
using FlyingClub.Models;
using FlyingClub.Models.ViewsModels;
using System.Web.Security;
using System.Collections.Generic;
using System;

namespace FlyingClub.Controllers
{ 
    public class MembersController : BeforeController
    {
        private FlyingClubDBEntities db = new FlyingClubDBEntities();

        //
        // GET: /Members/

        public ActionResult Index()
        {
            return RedirectToAction("CRUD", "Members");
        }

        #region CRUD

        //
        // GET: /Members/CRUD
        public ActionResult CRUD()
        {
            int _access = this.GetAccess();

            if (_access == 0)
                return RedirectToAction("LogOn", "Members");
            else if (_access == 1)
                return RedirectToAction("AccessError", "Home");
            else
                return View(db.Member.ToList());
        }

        //
        // GET: /Members/Details/5

        public ActionResult Details(int id)
        {
            int _access = this.GetAccess();

            if (_access == 0)
                return RedirectToAction("LogOn", "Members");
            else if (_access == 1)
            {
                if (!Session["ID"].Equals(id))
                    return RedirectToAction("AccessError", "Home");
                else
                {
                    Member member = db.Member.Single(m => m.ID == id);
                    return View(member);
                }
            }
            else
            {
                Member member = db.Member.Single(m => m.ID == id);
                return View(member);
            }
        }

        //
        // GET: /Members/Create

        public ActionResult Create()
        {
            int _access = this.GetAccess();

            if (_access == 0)
                return RedirectToAction("LogOn", "Members");
            else if (_access == 1)
                return RedirectToAction("AccessError", "Home");
            else
                return View();
        }

        //
        // POST: /Members/Create

        [HttpPost]
        public ActionResult Create(MemberCreateViewModel member)
        {
            int _access = this.GetAccess();

            if (_access == 0)
                return RedirectToAction("LogOn", "Members");
            else if (_access == 1)
                return RedirectToAction("AccessError", "Home");
            else
            {
                // Si c'est bon
                if (member.Firstname != null && member.Lastname != null && member.Password != null && member.Email != null && member.Gender != null)
                {

                    Member m = new Member();
                    if (member.InstructorNumber == null)
                        member.InstructorNumber = 0;
                    if (member.Wallet == null)
                        member.Wallet = 0;
                    m = this.MemberCreateViewModelToMember(member);
                    m.AdhesionDate = DateTime.Now;
                    m.AdhesionFees = DateTime.Now;
                    

                    member.Password = this.MD5Encrypt(member.Password);

                    db.Member.AddObject(m);
                    db.SaveChanges();

                    return RedirectToAction("Index");
                }
                else if(ModelState.IsValid)
                {
                    return View(member);
                }
                return View(member);
            }
        }

        //
        // GET: /Members/Edit/5

        public ActionResult Edit(int id)
        {
            int _access = this.GetAccess();

            if (_access == 0)
                return RedirectToAction("LogOn", "Members");
            else if (_access == 1)
            {
                if (!Session["ID"].Equals(id))
                    return RedirectToAction("AccessError", "Home");
                else
                {
                    Member member = db.Member.Single(m => m.ID == id);
                    return View(this.MemberToCreateViewModel(member));
                }
            }
            else
            {
                Member member = db.Member.Single(m => m.ID == id);
                return View(this.MemberToCreateViewModel(member));
            }
        }

        //
        // POST: /Members/Edit/5

        [HttpPost]
        public ActionResult Edit(MemberCreateViewModel member)
        {
            int _access = this.GetAccess();

            if (_access == 0)
                return RedirectToAction("LogOn", "Members");
            else if (_access == 1)
            {
                if (!Session["ID"].Equals(member.ID))
                {
                    return RedirectToAction("AccessError", "Home");
                }
                else
                {
                    if (member.Firstname != null && member.Lastname != null && member.Password != null && member.Email != null && member.Gender != null)
                    {
                        Member m = new Member();
                        if (member.InstructorNumber == null || member.InstructorNumber == 0)
                            member.InstructorNumber = 0;
                        if (member.Wallet == null)
                            member.Wallet = 0;
                        m = this.MemberCreateViewModelToMember(member);
                        db.Member.Attach(m);
                        db.ObjectStateManager.ChangeObjectState(m, EntityState.Modified);
                        db.SaveChanges();
                        return Redirect("/Members/Details/" + member.ID);
                    }
                    return View(member);
                }
                
            }
            else
            {
                if (member.Firstname != null && member.Lastname != null && member.Password != null && member.Email != null && member.Gender != null)
                {
                    Member m = new Member();
                    if (member.InstructorNumber == null)
                        member.InstructorNumber = 0;
                    if (member.Wallet == null)
                        member.Wallet = 0;
                    m = this.MemberCreateViewModelToMember(member);

                    db.Member.Attach(m);
                    db.ObjectStateManager.ChangeObjectState(m, EntityState.Modified);
                    db.SaveChanges();
                    return Redirect("/Members/Details/" + member.ID);
                }
                return View(member);
            }
        }

        //
        // GET: /Members/Delete/5

        public ActionResult Delete(int id)
        {
            int _access = this.GetAccess();

            if (_access == 0)
                return RedirectToAction("LogOn", "Members");
            else if (_access == 1)
                return RedirectToAction("AccessError", "Home");
            else
            {
                Member members = db.Member.Single(m => m.ID == id);
                return View(members);
            }
        }

        //
        // POST: /Members/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            int _access = this.GetAccess();

            if (_access == 0)
                return RedirectToAction("LogOn", "Members");
            else if (_access == 1)
                return RedirectToAction("AccessError", "Home");
            else
            {
                Member members = db.Member.Single(m => m.ID == id);
                db.Member.DeleteObject(members);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
        }

        //
        // GET: /Members/PayFees

        public ActionResult PayFees()
        {
            int _access = this.GetAccess();

            if (_access == 0)
                return RedirectToAction("LogOn", "Members");
            else
            {
                int memberID = (int)Session["ID"];
                Member member = db.Member.Single(x => x.ID == memberID);
                if (member.Wallet < 1000)
                {
                    ViewBag.NotEnoughMoney = true;
                }
                else
                {
                    ViewBag.NotEnoughMoney = false;
                    Transaction _transaction = new Transaction();
                    _transaction.Date = DateTime.Now;
                    _transaction.CreditID = 1;
                    _transaction.DebtorID = memberID;
                    _transaction.Description = "Fees " + Session["Lastname"].ToString() + " " + DateTime.Now.ToString();
                    db.Transaction.AddObject(_transaction);

                    member.Wallet -= 1000;
                    member.AdhesionFees = DateTime.Now;
                    db.Member.Attach(member);

                    db.SaveChanges();

                    Session["NeedToPayFees"] = false;

                    return RedirectToAction("Index", "Home");
                }
            }

            return View();
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

        [HttpGet]
        public ActionResult PasswordEdit(int id)
        {
            int _access = this.GetAccess();

            if (_access == 1)
            {
                if(Session["ID"].Equals(id))
                {
                    PasswordEdit pe = new PasswordEdit();
                    pe.ID = id;
                    return View(pe);
                }
            }
            else if (_access == 2)
            {
                PasswordEdit pe = new PasswordEdit();
                pe.ID = id;
                return View(pe);
            }
            return RedirectToAction("AccessError", "Home");
        }

        [HttpPost]
        public ActionResult PasswordEdit(PasswordEdit pe)
        {
            int _access = this.GetAccess();

                if (_access == 1)
                {
                    if ((int)Session["ID"] == pe.ID)
                    {
                        // Récupère le membre en cours
                        Member members = db.Member.Single(m => m.ID == pe.ID);

                        // Vérifie que l'encien correspond et que les 2 nouveaux correspondent
                        if (members.Password == this.MD5Encrypt(pe.OldPassword) && pe.NewPassword == pe.NewPasswordConfim)
                        {
                            // Change le mdp
                            members.Password = MD5Encrypt(pe.NewPassword);

                            // Enregistre le nouveau mdp dans la BDD
                            db.ObjectStateManager.ChangeObjectState(members, EntityState.Modified);
                            db.SaveChanges();
                            return Redirect("/Members/Details/" + members.ID);
                        }
                        ViewBag.ERRORMESSAGE = "Il y a une erreure dans votre formulaire";
                        pe.OldPassword = "";
                        pe.NewPassword = "";
                        pe.OldPassword = "";
                        return View(pe);
                    }
                    return View("AccessError");
                }
                else if (_access == 2)
                {
                    // Récupère le membre en cours
                    Member members = db.Member.Single(m => m.ID == pe.ID);
                    // Vérifie que les 2 nouveaux correspondent
                    if (pe.NewPassword == pe.NewPasswordConfim)
                    {
                        // Change le mdp
                        members.Password = MD5Encrypt(pe.NewPassword);

                        // Enregistre le nouveau mdp dans la BDD
                        db.ObjectStateManager.ChangeObjectState(members, EntityState.Modified);
                        db.SaveChanges();
                        return Redirect("/Members/Details/" + members.ID);
                    }
                    ViewBag.ERRORMESSAGE = "Les deux mots de passe ne correspondent pas";
                    pe.OldPassword = "";
                    pe.NewPassword = "";
                    pe.OldPassword = "";
                    return View(pe);
                }
                return View("AccessError");
        }
        #endregion 

        #region LogOn, LogOff
        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model)
        {
            if (ModelState.IsValid)
            {
                //model.Password = this.MD5Encrypt(model.Password);
                List<Member> members = db.Member.Where(x => x.Email == model.Email && x.Password == model.Password).ToList();
                if (members.Count > 0)
                {
                    Member member = members[0];
                    FormsAuthentication.SetAuthCookie(member.Email, true);

                    Session["ID"] = member.ID;
                    Session["Firstname"] = member.Firstname;
                    Session["Lastname"] = member.Lastname;

                    if (member.InstructorNumber != 0)
                        Session["InstructorNumber"] = member.InstructorNumber;

                    if (member.Staff.Equals(true))
                        Session["Staff"] = true;

                    // Informations pour le profiler
                    if (DateTime.Now.Day >= member.AdhesionFees.Day && DateTime.Now.Month >= member.AdhesionFees.Month && DateTime.Now.Year - member.AdhesionFees.Year > 0)
                        Session["NeedToPayFees"] = true;
                    else
                        Session["NeedToPayFees"] = false;

                    Session["Wallet"] = member.Wallet.ToString();

                    List<Flight> flights = db.Flight.Where(x => x.DepartureDate >= DateTime.Now && x.PilotID == member.ID && x.Validate == true).ToList();
                    if (flights.Count > 0)
                    {
                        Flight flight = flights[0];
                        Session["NextFlightDate"] = flight.DepartureDate.ToString();
                        Session["NextFlightID"] = flight.ID;
                    }

                    Session["NbToValidate"] = db.Flight.Count(x => x.PilotID == member.ID && x.DepartureDate >= DateTime.Now && (x.Validate == false || x.Validate == null));

                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", "Le nom d'utilisateur ou mot de passe fourni est incorrect.");
                }
            }
            else
            {
                ModelState.AddModelError("", "Le nom d'utilisateur ou mot de passe fourni est incorrect.");
            }

            return View(model);
        }

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            Session.Clear();

            return RedirectToAction("Index", "Home");
        }
        #endregion
    }
}